//
//  YWPersonPicker.m
//  YWPaymentPlatform
//
//  Created by 王通 on 2016/9/20.
//  Copyright © 2016年 YinWan. All rights reserved.
//

#import "CedarPersonPicker.h"

#import <AddressBookUI/AddressBookUI.h>
#import <AddressBook/AddressBook.h>

@interface CedarPersonPicker () <ABPeoplePickerNavigationControllerDelegate, UIAlertViewDelegate>

@property (strong, nonatomic) UIViewController *fatherController;
@property (strong, nonatomic) void (^didSelect)(NSString *phoneNumber);

@end

@implementation CedarPersonPicker

- (void)showPersionPickerWithController:(UIViewController *)controller
                         didSelectPhone:(void (^)(NSString *phoneNumber))didSelect {
    _fatherController = controller;
    _didSelect = [didSelect copy];
    //1. 获取授权状态
    ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
    CFErrorRef error = nil;
    //2. 创建 AddrssBook
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
    //3. 没有授权时就授权
    NSLog(@"%d",status);
    if (status == kABAuthorizationStatusNotDetermined) {
        __weak typeof(self) weakSelf = self;
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
            //3.1 判断是否出错
            if (error) {
                return;
            }
            //3.2 判断是否授权
            if (granted) {
                NSLog(@"已经授权");
                [weakSelf showPicker];
            } else {
                NSLog(@"没有授权");
            }
            //不为空 需要回收
            if (addressBook) {
                CFRelease(addressBook);
            }
        });
    } else if (status == kABAuthorizationStatusAuthorized) {
        [self showPicker];
        //不为空 需要回收
        if (addressBook) {
            CFRelease(addressBook);
        }
    } else {
        //YWAlert(@"请在【设置-隐私-通讯录】中开启权限");
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"请在【设置-隐私-通讯录】中开启权限" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
        //不为空 需要回收
        if (addressBook) {
            CFRelease(addressBook);
        }
    }
}

- (void)showPicker {
    if (!_fatherController) {
        return;
    }
    ABPeoplePickerNavigationController *peoplePickerController = [[ABPeoplePickerNavigationController alloc] init];
    peoplePickerController.peoplePickerDelegate = self;
    peoplePickerController.displayedProperties = [NSArray arrayWithObject:[NSNumber numberWithInt:kABPersonPhoneProperty]];
    if([[UIDevice currentDevice].systemVersion floatValue] >= 8.0){
        peoplePickerController.predicateForSelectionOfPerson = [NSPredicate predicateWithValue:false];
    }
    if (@available(iOS 13.0, *)) {
       _fatherController.modalPresentationStyle  =  UIModalPresentationFullScreen;
    }
    
    [_fatherController presentViewController:peoplePickerController animated:YES completion:^{
    }];
}

#pragma mark - 
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        //8.0以上处理
        if([[UIDevice currentDevice].systemVersion floatValue] >= 8.0){
            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }
        }
    }
}

#pragma mark -ABPeoplePickerNavigationControllerDelegate
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker {
    [peoplePicker dismissViewControllerAnimated:YES completion:^{
    }];
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    //phoneNumber
    ABMutableMultiValueRef phoneMulti = ABRecordCopyValue(person, kABPersonPhoneProperty);
    NSMutableArray *phones = [NSMutableArray array];
    for (int i = 0; i < ABMultiValueGetCount(phoneMulti); i++) {
        CFTypeRef phoneRef = ABMultiValueCopyValueAtIndex(phoneMulti, i);
        [phones addObject:(__bridge NSString *)phoneRef];
        CFRelease(phoneRef);
    }
    NSString *phoneNumber = @"";
    if (property == kABPersonPhoneProperty) {
        if (phones.count > 0) {
            if ((int)identifier < [phones count]) {
                phoneNumber = [phones objectAtIndex:identifier];
            } else {
                phoneNumber = AvoidNullString(phones[0]);
            }
        } else {
            
        }
    }
    CFRelease(phoneMulti);
    if (_didSelect) {
        _didSelect(phoneNumber);
    }
    [peoplePicker dismissViewControllerAnimated:YES completion:^{
    }];
    
    return NO;
}

-(void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    
    //phoneNumber
    ABMutableMultiValueRef phoneMulti = ABRecordCopyValue(person, kABPersonPhoneProperty);
    NSMutableArray *phones = [NSMutableArray array];
    for (int i = 0; i < ABMultiValueGetCount(phoneMulti); i++) {
        CFTypeRef phoneRef = ABMultiValueCopyValueAtIndex(phoneMulti, i);
        [phones addObject:(__bridge NSString *)phoneRef];
        CFRelease(phoneRef);
    }
    NSString *phoneNumber = @"";
    if (property == kABPersonPhoneProperty) {
        if (phones.count > 0) {
            if ((int)identifier < [phones count]) {
                phoneNumber = [phones objectAtIndex:identifier] ;
            } else {
                phoneNumber =AvoidNullString(phones[0]);
            }
        } else {
        }
    }
    CFRelease(phoneMulti);
    if (_didSelect) {
        _didSelect(phoneNumber);
    }
    [peoplePicker dismissViewControllerAnimated:YES completion:^{
    }];
}

@end
